<template>
  <div ref="scEcharts" :style="{ height: props.height, width: props.width }"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import T from './echarts-theme-T';
import { computed, nextTick, onActivated, onDeactivated, onMounted, ref, watch } from 'vue';

echarts.registerTheme('T', T);

const props = withDefaults(defineProps<{
  height: string,
  width?: string,
  nodata?: boolean,
  option?: echarts.EChartsCoreOption
}>(), {
  height: "100%",
  width: "100%",
  nodata: false,
  option: () => ({})
})

const myChart = ref<echarts.ECharts | null>(null);

const unwarp = (obj: echarts.ECharts) => (obj && ((obj as unknown as { __v_raw: string }).__v_raw || obj.valueOf() || obj) as echarts.ECharts);
watch(() => props.option, val => {
  nextTick(() => {
    unwarp(myChart.value! as echarts.ECharts).setOption(val)
  })
})

const myOptions = computed<echarts.EChartsCoreOption>(() => props.option || {});

const isActivat = ref(false);
onActivated(() => {
  if (!isActivat.value) {
    nextTick(() => {
      myChart.value?.resize();
    });
  }
})

onDeactivated(() => {
  isActivat.value = false;
})

onMounted(() => {
  isActivat.value = true;
  nextTick(draw);
})

const scEcharts = ref<HTMLDivElement | null>(null)
const draw = () => {
  const chart = echarts.init(scEcharts.value!, 'T');
  chart.setOption(myOptions.value);
  myChart.value = chart;
  window.addEventListener('resize', () => chart.resize());
};

// export default {
// 	...echarts,
// 	name: 'scEcharts',
// 	props: {
// 		height: { type: String, default: '100%' },
// 		width: { type: String, default: '100%' },
// 		nodata: { type: Boolean, default: false },
// 		option: {
// 			type: Object,
// 			default: () => {},
// 		},
// 	},
// 	data() {
// 		return {
// 			isActivat: false,
// 			myChart: null,
// 		};
// 	},
// 	watch: {
// 		option: {
// 			deep: true,
// 			handler(v) {
// 				this.$nextTick(() => {
// 					unwarp(this.myChart).setOption(v);
// 				});
// 			},
// 		},
// 	},
// 	computed: {
// 		myOptions: function () {
// 			return this.option || {};
// 		},
// 	},
// 	activated() {
// 		if (!this.isActivat) {
// 			this.$nextTick(() => {
// 				this.myChart.resize();
// 			});
// 		}
// 	},
// 	deactivated() {
// 		this.isActivat = false;
// 	},
// 	mounted() {
// 		this.isActivat = true;
// 		this.$nextTick(() => {
// 			this.draw();
// 		});
// 	},
// 	methods: {
// 		draw() {
// 			let myChart = echarts.init(this.$refs.scEcharts, 'T');
// 			myChart.setOption(this.myOptions);
// 			this.myChart = myChart;
// 			window.addEventListener('resize', () => myChart.resize());
// 		},
// 	},
// };
</script>
